import { Card, Input, message, Select, Table } from 'antd';
import React, { Component } from 'react';
import { connect } from 'dva';
import SearchForm from '../../components/AutoForm/SearchForm';
import EditForm from '../../components/AutoForm/EditForm';

const searchFields = [
  {
    cols: [
      {
        md: 6,
        label: 'LOAD号',
        name: 'loadNo',
        component: <Input placeholder="请输入LOAD号" />,
      },
      {
        md: 6,
        label: '订单状态',
        name: 'status',
        component: (
          <Select placeholder="请输入订单状态">
            <Option value="GATHERING">待收款</Option>
            <Option value="INVOICE_HALF">开票(非足额)</Option>
            <Option value="INVOICE">开票(足额)</Option>
          </Select>
        ),
      },
    ],
  },
];

@connect(({ loading, auditOrder }) => ({
  tableLoading: loading.effects['auditOrder/invoicePage'],
  formLoading: loading.effects['auditOrder/invoice'],
  tableData: auditOrder.invoicePageList,
  pagination: auditOrder.pagination,
  columns: auditOrder.columns,
  selectionIds: auditOrder.selectionIds,
  selectedRows: auditOrder.selectedRows,
  invoiceModal: auditOrder.invoiceModal,
  invoiceForm: auditOrder.invoiceForm,
  invoiceRows: auditOrder.invoiceRows,
}))
export default class NestTable extends Component {
  state = {
    sumText: '选中合计费用：0',
    searchValues: {
      status: {
        name: 'status',
        value: 'GATHERING'
      }
    },
  };

  rowClassName = (record, index) => {
    if (record.status === 'GATHERING') {
      return 'orderParent';
    }
  };

  componentDidMount() {
    this.handleSearch();
  }


  handleSearch = (flag) => {
    const { searchValues } = this.state;
    const { dispatch, pagination } = this.props;
    let pageParam = { pageSize: pagination.pageSize, current: flag==='btn' ? 1 : pagination.current };
    let searchParam = {};
    Object.keys(searchValues).map(key => {
      searchParam[key] = searchValues[key]['value'];
    });
    const param = {
      ...searchParam,
      ...pageParam,
      flag: 'ticketPay',
    };
    dispatch({
      type: 'auditOrder/invoicePage',
      payload: param,
    });
  };

  handleSearchChange = fields => {
    this.setState({ searchValues: fields });
  };

  onChange = (selectedRowKeys, selectedRows) => {
    let sum = 0.0;
    selectedRows.forEach(row => {
      sum += row.feeSum;
    });
    this.setState({ sumText: `选中合计费用：${sum}` });
    const { dispatch } = this.props;
    dispatch({
      type: 'auditOrder/handleSelection',
      payload: { selectedRowKeys, selectedRows },
    });
  };

  handleModalVisible = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'auditOrder/handleInvoiceModal',
    });
  };

  handleModalChange = fields => {
    const { dispatch } = this.props;
    dispatch({
      type: 'auditOrder/handleInvoiceChange',
      payload: { fields },
    });
  };

  handleInvoiceSub = fields => {
    const { dispatch, selectedRows } = this.props;
    const params = {
      tmsInvoice: fields,
      orders: selectedRows,
    };
    dispatch({
      type: 'auditOrder/invoice',
      payload: params,
    }).then(() => {
      this.handleSearch();
      this.handleModalVisible();
    });
  };

  /* onMoney = () => {
    const { dispatch, selectedRows } = this.props;
    if (!selectedRows.length) {
      return message.error('请选要收款的数据！');
    }
    selectedRows.forEach(row => {
      if (row.status !== 'INVOICE') {
        return message.error('状态异常！');
      }
    });
    let ids = [];
    selectedRows.forEach(row => {
      ids.push(row.id);
    });
    dispatch({
      type: 'auditOrder/pay',
      payload: ids,
    }).then(() => {
      this.handleSearch();
    });
  };*/

  onTicket = () => {
    const { dispatch, selectedRows } = this.props;
    if (!selectedRows.length) {
      return message.error('请选要开票的数据！');
    }
    selectedRows.forEach(row => {
      if (row.status !== 'GATHERING') {
        return message.error('状态异常！');
      }
    });
    dispatch({
      type: 'auditOrder/checkInvoice',
      payload: selectedRows,
    });
  };

  handleReject = () => {
    const { dispatch, selectionIds } = this.props;
    if (selectionIds.length !== 1) {
      return message.error('请选一条要驳回数据！');
    }
    dispatch({
      type: 'auditOrder/invoiceReject',
      payload: selectionIds[0]
    }).then(() => {
      this.handleSearch()
    })
  }

  render() {
    const {
      columns,
      pagination,
      tableLoading,
      tableData,
      dispatch,
      invoiceRows,
      invoiceForm,
      invoiceModal,
      formLoading,
    } = this.props;
    const { searchValues } = this.state;
    pagination.onChange = (page, pageSize) => {
      let searchParam = {};
      Object.keys(searchValues).map(key => {
        searchParam[key] = searchValues[key]['value'];
      });
      dispatch({
        type: 'auditOrder/invoicePage',
        payload: {
          ...searchParam,
          current: page,
          pageSize,
        },
      });
    };
    pagination.onShowSizeChange = (current, size) => {
      let searchParam = {};
      Object.keys(searchValues).map(key => {
        searchParam[key] = searchValues[key]['value'];
      });
      dispatch({
        type: 'auditOrder/invoicePage',
        payload: {
          ...searchParam,
          current: current,
          pageSize: size,
        },
      });
    };

    const rowSelection = {
      type: 'checkbox',
      selections: this.props.selectedRows,
      selectedRowKeys: this.props.selectionIds,
      onChange: this.onChange,
      getCheckboxProps: record => ({
        disabled: record.parentId,
      }),
    };

    return (
      <Card bodyStyle={{ padding: 0 }}>
        <SearchForm
          header="开票&收款->操作"
          moneyText="收款"
          layout="inline"
          onFieldsChange={this.handleSearchChange}
          onSubmit={() => {this.handleSearch('btn')}}
          isSum={true}
          sumText={this.state.sumText}
          isTicket={true}
          isReject={true}
          onTicket={this.onTicket}
          onReject={this.handleReject}
          fields={searchFields}
          fieldValue={searchValues}
        />
        <Table
          loading={tableLoading}
          columns={columns}
          rowSelection={rowSelection}
          dataSource={tableData}
          size="small"
          bordered
          rowKey="id"
          scroll={{ x: 'max-content' }}
          rowClassName={this.rowClassName}
          pagination={pagination}
        />
        <EditForm
          title="开票"
          rows={invoiceRows}
          fieldValue={invoiceForm}
          onFieldsChange={this.handleModalChange}
          onCancel={this.handleModalVisible}
          onOk={this.handleInvoiceSub}
          confirmLoading={formLoading}
          visible={invoiceModal}
        />
      </Card>
    );
  }
}
